package com.hang.gymmanager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hang.gymmanager.Enum.CommonConstant;
import com.hang.gymmanager.Enum.CommonEnum;
import com.hang.gymmanager.Enum.UserTypeEnum;
import com.hang.gymmanager.convert.PojoConvert;
import com.hang.gymmanager.entity.UserInfoEntity;
import com.hang.gymmanager.entity.WalletEntity;
import com.hang.gymmanager.exception.BusinessException;
import com.hang.gymmanager.mapper.UserInfoMapper;
import com.hang.gymmanager.mapper.WalletMapper;
import com.hang.gymmanager.req.UpdatePasswordReq;
import com.hang.gymmanager.req.UserRegisterReq;
import com.hang.gymmanager.service.UserService;
import com.hang.gymmanager.util.PasswordEncodeUtil;
import com.hang.gymmanager.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserInfoMapper userInfoMapper;
    private final PojoConvert convert;

    private final WalletMapper walletMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userRegister(UserRegisterReq req) {
        //校验身份证号是否正确
        String regex = "^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\\d{3}([0-9Xx])$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(req.getIdNo());
        Boolean isValid = matcher.matches();
        if(!isValid){
            throw new BusinessException("身份证号不符合格式");
        }
        QueryWrapper<UserInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserInfoEntity::getTelephone,req.getTelephone());
        Long count = userInfoMapper.selectCount(wrapper);
        if(count>0){
            throw new BusinessException("该手机号已存在");
        }

        UserInfoEntity entity = convert.registerReq2Entity(req);
        //对密码进行加密处理
        String codePassword = PasswordEncodeUtil.passwordEncode(req.getPassword(), CommonConstant.PASSWORD_SALT);
        entity.setPassword(codePassword);
        //其它参数的填充
        entity.setType(UserTypeEnum.NORMAL.getValue())
                .setRecFlag(CommonEnum.YES.getValue())
                .setCreateTime(LocalDateTime.now())
                .setEditTime(LocalDateTime.now());
        userInfoMapper.insert(entity);
        WalletEntity walletEntity = new WalletEntity();
        walletEntity.setUserId(entity.getUserId());
        walletEntity.setBalance(new BigDecimal(0));
        walletMapper.insert(walletEntity);
    }

    @Override
    public void updatePassword(UpdatePasswordReq req) {
        Integer userId = SecurityUtils.getUserId();
        QueryWrapper<UserInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserInfoEntity::getUserId,userId);
        UserInfoEntity user = userInfoMapper.selectOne(wrapper);
        if(user==null){
            throw new BusinessException("查无此人请重新确认用户id");
        }
        String codeOld = PasswordEncodeUtil.passwordEncode(req.getOldPwd(), CommonConstant.PASSWORD_SALT);
        if(!StrUtil.equals(codeOld,user.getPassword())){
            throw new BusinessException("旧密码不一致");
        }
        if(!StrUtil.equals(req.getNewPwd(),req.getCheckNewPwd())){
            throw new BusinessException("新密码不一致");
        }
        String codeNew = PasswordEncodeUtil.passwordEncode(req.getNewPwd(), CommonConstant.PASSWORD_SALT);
        user.setPassword(codeNew);
        userInfoMapper.updateById(user);
    }
}
